package dice.sinanya.start;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class ListenPort {
    private static final Logger logger = LogManager.getLogger(ListenPort.class.getName());

    public ListenPort() {
    }

    /***
     * 测试主机Host的port端口是否被使用
     * @param host
     * @param port
     * @throws UnknownHostException
     */
    public static boolean isPortUsing(String host, int port) throws UnknownHostException {
        boolean flag = false;
        InetAddress Address = InetAddress.getByName(host);
        try {
            Socket socket = new Socket(Address, port);  //建立一个Socket连接
            flag = true;
        } catch (ConnectException ignore) {
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return flag;
    }

    /**
     * 测试本机端口是否被使用
     *
     * @param port
     * @return
     */
    public boolean listenPort(int port) {
        boolean flag = true;
        try {
            //如果该端口还在使用则返回true,否则返回false,127.0.0.1代表本机
            flag = isPortUsing("127.0.0.1", port);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return flag;
    }
}
